package com.once;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.SimpleAdapter;

import com.alibaba.fastjson.JSON;
import com.hjq.toast.ToastUtils;
import com.once.databinding.ActivityGuigeBinding;
import com.once.db.DaoSession;
import com.once.db.POJODao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.once.MainActivity.txt_company;
import static com.once.MainActivity.txt_date;

/**
 * @author 张成
 */
public class GuigeActivity extends Activity {
    // 表格定位的左上角X和右上角Y
    private final static int START_X = 140;
    // 表格的宽度
    private static final float GRID_WIDTH = 50f;
    private static final float GRID_HEIGHT = 40f;
    public static String txt_norms;
    private static int STARTY;
    private static int CURRX;
    private static int CURRY;
    DecimalFormat df = new DecimalFormat("0.00");

    private DaoSession daoSession;
    private List<POJO> dojos;
    private ActivityGuigeBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityGuigeBinding.inflate(getLayoutInflater());

        setContentView(binding.getRoot());
        daoSession = ((MyApplication) getApplication()).getDaoSession();


        binding.listview.setOnItemClickListener((adapterView, view, i, l) -> {
            Map<String, String> item = (Map<String, String>) adapterView.getItemAtPosition(i);
            GuigeActivity.txt_norms = item.get("norms");
            startActivity(new Intent(GuigeActivity.this, Details.class));
        });
        binding.listview.setOnItemLongClickListener((adapterView, view, i, l) -> {
            final Map<String, String> item = (Map<String, String>) adapterView.getItemAtPosition(i);
            AlertDialog.Builder builder = new AlertDialog.Builder(GuigeActivity.this);
            builder.setTitle("重要提示");
            builder.setMessage("是否删除「" + item.get("norms") + "」的全部数据！");
            builder.setCancelable(true);            //点击对话框以外的区域是否让对话框消失
            //设置正面按钮
            builder.setPositiveButton("确定", (dialog, which) -> {
                daoSession.queryBuilder(POJO.class)
                        .where(POJODao.Properties.Norms.eq(item.get("norms")))
                        .where(POJODao.Properties.Company.eq(txt_company))
                        .where(POJODao.Properties.Category.eq(MainActivity.txt_category))
                        .buildDelete()
                        .executeDeleteWithoutDetachingEntities();
                onStart();
            });
            //设置反面按钮
            builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
            builder.show();
            return true;
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        dojos = daoSession.queryRaw(POJO.class, "where category=? and company=? ", MainActivity.txt_category, MainActivity.txt_company);

        ArrayList<Map<String, String>> arrayList = new ArrayList<>();
        for (POJO dojo : dojos) {
            Map<String, String> map = new HashMap<>(1);
            ArrayList<Double> list = (ArrayList<Double>) JSON.parseArray(dojo.getWeight(), Double.class);

            map.put("norms", dojo.getNorms());
            map.put("text", list.size() + "件\t" + df.format(getsum(list)) + "kg");
            arrayList.add(map);
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, arrayList, R.layout.list_item, new String[]{"norms", "text"}, new int[]{R.id.item_title, R.id.item_text});

        binding.listview.setAdapter(simpleAdapter);

    }

    public void finish(View view) {
        if (dojos == null || dojos.size() == 0) {
            return;
        }
        STARTY = 120;
        double total = 0;
        double totalWeight = 0;
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        paint.setTextSize(20);
        Bitmap bitmap = Bitmap.createBitmap(1754, 1240, Bitmap.Config.ARGB_8888);
        Canvas myCanvas = new Canvas(bitmap);
        myCanvas.drawColor(Color.WHITE);
        Paint mPaint = new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setTextSize(26);
        mPaint.setAntiAlias(true);
        Paint titlePaint = new Paint();
        titlePaint.setColor(Color.BLACK);
        titlePaint.setTextSize(35);
        //设置抗锯齿
        titlePaint.setAntiAlias(true);


        for (POJO dojo : dojos) {

            ArrayList<Double> arrayList = (ArrayList<Double>) JSON.parseArray(dojo.getWeight(), Double.class);

            List<List<Double>> lists = splitList(arrayList, 10);
            int row = lists.size() + 1;
            Paint paintRect = new Paint();
            paintRect.setColor(Color.BLACK);
            paintRect.setStrokeWidth(2);
            paintRect.setStyle(Paint.Style.STROKE);
            paintRect.setAntiAlias(true);
            int col = 20;
            myCanvas.drawRect(START_X, STARTY, START_X + GRID_WIDTH * 1.5f * col, STARTY
                    + GRID_HEIGHT * row, paintRect);


            paintRect.setStrokeWidth(1);
            myCanvas.drawRect(START_X, STARTY - GRID_HEIGHT, START_X + GRID_WIDTH * 1.5f * col, STARTY, paintRect);
            total = total + arrayList.size();

            totalWeight += getsum(arrayList);
            myCanvas.drawText(dojo.getNorms() + " \t " + "数量：" + arrayList.size() + "件\t" + df.format(getsum(arrayList)) + "kg", START_X + 20, STARTY - 15, paint);

            //横线
            for (int kk = 0; kk < row - 1; kk++) {
                myCanvas.drawLine(START_X, STARTY + (kk + 1) * GRID_HEIGHT, START_X
                                + col * GRID_WIDTH * 1.5f, STARTY + (kk + 1) * GRID_HEIGHT,
                        paintRect);
            }
            //竖线
            CURRX = START_X;

            for (int j = 0; j < col; j++) {
                if (j % 2 == 1) {
                    CURRX += GRID_WIDTH * 2F;
                    myCanvas.drawLine(CURRX, STARTY, CURRX, STARTY + row * GRID_HEIGHT, paintRect);
                    myCanvas.drawText("重量", CURRX - 70, STARTY + GRID_HEIGHT - 12, paint);
                } else {
                    CURRX += GRID_WIDTH;
                    myCanvas.drawLine(CURRX, STARTY, CURRX, STARTY + row * GRID_HEIGHT, paintRect);
                    myCanvas.drawText("货号", CURRX - 45, STARTY + GRID_HEIGHT - 12, paint);
                }
            }

            Paint paint1 = new Paint();
            paint1.setColor(Color.BLACK);
            paint1.setAntiAlias(true);
            paint1.setTextSize(18);
            paint1.setTypeface(Typeface.create("宋体", Typeface.BOLD_ITALIC));

            //填数据
            int text = 0;
            CURRY = (int) (STARTY + GRID_HEIGHT);
            for (List<Double> list : lists) {
                CURRY += GRID_HEIGHT;
                CURRX = (int) (START_X - GRID_WIDTH);
                for (int k = 0; k < list.size() * 2; k++) {
                    CURRX += GRID_WIDTH * 1.5f;
                    if (k % 2 == 0) {
                        myCanvas.drawText(++text + "", CURRX - 16, CURRY - 12, paint1);
                    } else {
                        myCanvas.drawText(String.valueOf(list.get((k + 1) / 2 - 1)), CURRX - 35, CURRY - 12, paint);
                    }

                }
            }

            STARTY = (int) (STARTY + row * GRID_HEIGHT) + 60;
        }


        myCanvas.drawText("出库清单", 780, 38, titlePaint);
        myCanvas.drawText("订货单位：" + txt_company, 160, 38, mPaint);
        myCanvas.drawText(MainActivity.txt_category, 180, 70, mPaint);
        myCanvas.drawText("合计重量：" + df.format(totalWeight) + "kg", 450, 70, mPaint);
        myCanvas.drawText("数量：" + df.format(total) + "件", 900, 70, mPaint);
        myCanvas.drawText("单位：kg", 1200, 70, mPaint);
        myCanvas.drawText("日期：" + txt_date, 1400, 70, mPaint);


        saveBitmap(bitmap, new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(new Date()) + txt_company + ".jpg");
    }


    private double getsum(ArrayList<Double> list) {
        double temp = 0;
        for (Double aDouble : list) {
            temp += aDouble;
        }
        return temp;
    }

    public void start(View view) {
        txt_norms = binding.guige.getText() + "";
        if (TextUtils.isEmpty(txt_norms)) {
            ToastUtils.show("规格不可为空！");
            return;
        }
        startActivity(new Intent(this, Details.class));
    }

    public void saveBitmap(Bitmap bitmap, String bitName) {

        String fileName;
        File file;
        // 小米手机
        if ("xiaomi".equals(Build.BRAND)) {
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else if ("Huawei".equals(Build.BRAND)) {
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else {
            // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);

        if (file.exists()) {
            boolean delete = file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
                // 插入图库
                MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), bitName, null);
            }
            ToastUtils.show("成功保存到系统相册");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
        // 发送广播，通知刷新图库的显示
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));

    }


    public List<List<Double>> splitList(ArrayList<Double> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return null;
        }

        List<List<Double>> result = new ArrayList<>();

        int size = list.size();
        int count = (size + len - 1) / len;

        for (int i = 0; i < count; i++) {
            List<Double> subList = list.subList(i * len, (Math.min((i + 1) * len, size)));
            result.add(subList);
        }
        return result;
    }


}
